package com.savi.myapplication;

import androidx.annotation.NonNull;
import androidx.core.app.ActivityCompat;
import androidx.fragment.app.Fragment;
import androidx.viewpager2.widget.ViewPager2;

import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.os.Build;
import android.os.Bundle;
import android.os.Environment;
import android.provider.Settings;
import android.view.View;
import android.widget.LinearLayout;

import com.google.android.material.tabs.TabLayout;
import com.google.android.material.tabs.TabLayoutMediator;
import com.savi.myapplication.adapter.ToDoTabFragmentAdapter;
import com.savi.myapplication.fragment.AirdropCardFragment;
import com.savi.myapplication.fragment.CheckListFragment;
import com.savi.myapplication.fragment.DisclaimerReportFragment;
import com.savi.myapplication.fragment.FlyTimeFragment;
import com.savi.myapplication.fragment.FuelCardFragment;
import com.savi.myapplication.fragment.HeavyLandingCardFragment;
import com.savi.myapplication.fragment.LongEnduranceCardFragment;
import com.savi.myapplication.fragment.RecordCardFragment;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

public class FlyCardActivity extends BaseActivity implements View.OnClickListener {

    //底部菜单栏
    private LinearLayout ll_nav_bottom;

    //资料
    private LinearLayout ll_doc;
    //飞行卡片
    private LinearLayout ll_fly_card;
    //性能
    private LinearLayout ll_performance;
    //设置
    private LinearLayout ll_setting;

    ///tab显示 start
    private TabLayout mTabLayout ;

    private ViewPager2 mViewPager2ToDo;

    //界面视图列表
    private List<Fragment> fragmentList;

    private static FlyCardActivity instance;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        instance = this;
        setContentView(R.layout.activity_main_launch);

        //动态申请权限，相机扫描需要的，读写、相机、聚焦
        if (Build.VERSION.SDK_INT >= 23) {
            String[] permissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE};

            List<String> permissionList = new ArrayList<>();

            //SDK>30 除了在manifest.xml添加 android:requestLegacyExternalStorage="true"
            //还需要进行在 ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION 进行授权才能访问 本地数据库等文件
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.R) {
                if (!Environment.isExternalStorageManager()) {
                    startActivityForResult(new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION), 200);
                }

            }
            for (String str : permissions) {
//                if (checkSelfPermission(this, permissions[i]) != PackageManager.PERMISSION_GRANTED) {
                if (ActivityCompat.checkSelfPermission(this, str) != PackageManager.PERMISSION_GRANTED) {

                    permissionList.add(str);
                }
            }
            Arrays.stream(permissions).forEach(e -> System.out.println("========20230719 ceshi" + e));
            if (permissionList.size() <= 0) {


                newLayout();
            } else {
                //存在为允许的权限，重新申请
                this.requestPermissions(permissions, 102);
            }

        }



    }


    /**
     * 卡片TAB 布局显示
     */
    private void newLayout(){


        //==============tab切换 通报、更新日志、年度任务完成情况 start================
        mTabLayout = (TabLayout) findViewById(R.id.tab_tb_todo);
        mTabLayout.addTab(mTabLayout.newTab().setText("时间卡片"));
        mTabLayout.addTab(mTabLayout.newTab().setText("成绩单"));
        mTabLayout.addTab(mTabLayout.newTab().setText("加油卡片"));
        mTabLayout.addTab(mTabLayout.newTab().setText("空投卡片"));
        mTabLayout.addTab(mTabLayout.newTab().setText("长航时卡片"));
        mTabLayout.addTab(mTabLayout.newTab().setText("重着陆卡片"));
        mTabLayout.addTab(mTabLayout.newTab().setText("免责报告"));
        mTabLayout.addTab(mTabLayout.newTab().setText("考核检验单"));

        mViewPager2ToDo = (ViewPager2) findViewById(R.id.vp_todo);
        fragmentList = new ArrayList<>();
        FlyTimeFragment flyTimeFragment = FlyTimeFragment.newInstance("", "");
        RecordCardFragment recordCardFragment = RecordCardFragment.newInstance("", "");
        FuelCardFragment fuelCardFragment = FuelCardFragment.newInstance("","");
        AirdropCardFragment airdropCardFragment = AirdropCardFragment.newInstance("", "");
        LongEnduranceCardFragment longEnduranceCardFragment = LongEnduranceCardFragment.newInstance("", "");
        HeavyLandingCardFragment heavyLandingCardFragment = HeavyLandingCardFragment.newInstance("", "");
        DisclaimerReportFragment disclaimerReportFragment = DisclaimerReportFragment.newInstance("", "");
        CheckListFragment checkListFragment = CheckListFragment.newInstance("", "");
//        TabUpdateLogFragment tabUpdateLogFragment = TabUpdateLogFragment.newInstance("", "");
//        TabTaskCompleteFragment tabTaskCompleteFragment = TabTaskCompleteFragment.newInstance("", "");

        fragmentList.add(flyTimeFragment);
        fragmentList.add(recordCardFragment);
        fragmentList.add(fuelCardFragment);
        fragmentList.add(airdropCardFragment);
        fragmentList.add(longEnduranceCardFragment);
        fragmentList.add(heavyLandingCardFragment);
        fragmentList.add(disclaimerReportFragment);
        fragmentList.add(checkListFragment);
//        fragmentList.add(tabUpdateLogFragment);
//        fragmentList.add(tabTaskCompleteFragment);


        ToDoTabFragmentAdapter toDoTabFragmentAdapter = new ToDoTabFragmentAdapter(getSupportFragmentManager(), getLifecycle(), fragmentList);
        mViewPager2ToDo.setAdapter(toDoTabFragmentAdapter);

        initTabLayout(mTabLayout, mViewPager2ToDo);
        //取消每项tab长安显示的tap
        for (int i = 0; i < mTabLayout.getTabCount(); i++) {
            TabLayout.Tab tab = mTabLayout.getTabAt(i);
            if (tab != null) {
                tab.view.setLongClickable(false);

                tab.view.setTooltipText(null);
            }
        }
        mViewPager2ToDo.setUserInputEnabled(false);
        //===============tab切换 通报、更新日志、年度任务完成情况end==============

    }

    /**
     * 初始化TableLayout
     *
     * @param tabLayout  tab
     * @param viewPager2 viewpage
     */
    public void initTabLayout(TabLayout tabLayout, ViewPager2 viewPager2) {

        TabLayoutMediator tabLayoutMediator = new TabLayoutMediator(tabLayout, viewPager2,true,false, new TabLayoutMediator.TabConfigurationStrategy() {
            @Override
            public void onConfigureTab(@NonNull TabLayout.Tab tab, int position) {
                if (position == 0) {
                    tab.setText("时间卡片");

                } else if (position == 1) {

                    tab.setText("成绩单");

                } else if (position == 2) {
                    tab.setText("加油卡片");

                } else if (position == 3) {

                    tab.setText("空投卡片");

                } else if (position == 4) {
                    tab.setText("长航时卡片");

                } else if (position == 5) {

                    tab.setText("重着陆卡片");

                } else if (position == 6) {
                    tab.setText("免责报告");

                }else if (position == 7) {
                    tab.setText("考核检验单");

                }
            }

        });
        tabLayoutMediator.attach();

    }

    @Override
    public void onClick(View v) {

    }


    /**
     * 扫码回调
     *
     * @param requestCode
     * @param resultCode
     * @param data
     */
    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
//        LanguageUtil.changeAppLanguage(this, PrefUtils.getLanguage(this)); // onCreate 之前调用 否则不起作用
        super.onActivityResult(requestCode, resultCode, data);

        //sdk>=30后需要使用的权限申请
        if (requestCode == 200 && Build.VERSION.SDK_INT > Build.VERSION_CODES.R) {
            if (Environment.isExternalStorageManager()) {
//                isRefuse = false;
            } else {
//                isRefuse = true;
                startActivityForResult(new Intent(Settings.ACTION_MANAGE_ALL_FILES_ACCESS_PERMISSION), 200);
            }
        }

    }

    /**
     * 权限 回调
     *
     * @param requestCode
     * @param permissions
     * @param grantResults
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        boolean haspermission = false;
        // 读写 相机 聚焦
        if (requestCode == 102) {
            for (int i = 0; i < grantResults.length; i++) {

                if (grantResults[i] == -1) {
                    haspermission = true;
                }

            }

            if (haspermission) {
                //跳转到系统设置权限页面，或者直接关闭页面，不让他继续访问
//                permissionDialog();
            } else {
                newLayout();


            }


        }
    }

    public static FlyCardActivity getActivity() {
        return instance;
    }
}